<script setup>
import { ref, toRefs, defineExpose, watch } from "vue";
import { useDrawerStore } from "@/store/drawerDataStores.js";
import { message } from "@/utils/message";

const drawerStore = useDrawerStore();
const props = defineProps({
  devVarTableSelectedItem: {
    type: Object,
    default() {
      return {};
    }
  },
  publicForm: {
    type: Object,
    default() {
      return {};
    }
  }
});
const { devVarTableSelectedItem, publicForm } = toRefs(props);
const emit = defineEmits(["childFormObj"]);

const ruleFormRef = ref(),
  ruleFormLeftRef = ref(),
  ruleForm = ref({
    protocolType: undefined, // 协议类型
    protocolAddress: undefined, //协议地址
    protocolNumber: undefined //协议数量
  }),
  ruleFormLeft = ref({
    passiveAddress: undefined
  }),
  tableData = ref([]);
// 确定按钮
const confirmClick = () => {
  if (
    ruleForm.value.protocolType &&
    ruleForm.value.protocolAddress &&
    ruleForm.value.protocolNumber
  ) {
    // 检查数组中是否已经存在完全相同的对象
    let isDuplicate = tableData.value.some(obj => {
      return (
        obj.protocolType === ruleForm.value.protocolType &&
        obj.protocolAddress === ruleForm.value.protocolAddress &&
        obj.protocolNumber === ruleForm.value.protocolNumber
      );
    });
    if (!isDuplicate) {
      tableData.value.push({
        protocolType: ruleForm.value.protocolType,
        protocolAddress: ruleForm.value.protocolAddress,
        protocolNumber: ruleForm.value.protocolNumber
      });
    }
  }
};
// 删除按钮
const deleteClick = () => {
  if (selectedKey.value.length === 0) {
    message("请选择要删除的数据", { type: "warning" });
    return;
  }
  tableData.value = tableData.value.filter(
    row => !selectedKey.value.includes(row)
  );
  selectedKey.value = [];
};
// table多选事件
const selectedKey = ref([]);
const handleSelectionChange = keys => {
  selectedKey.value = keys;
};
// 配置按钮
const configClick = () => {
  // 定义一个名为 configClick 的箭头函数
  if (selectedKey.value.length > 0 && ruleFormLeft.value.passiveAddress) {
    let readInfo = [];
    for (let i = 0; i < tableData.value.length; i++) {
      readInfo.push({
        // 将每一项数据对象推入 readInfo 数组
        type: tableData.value[i].protocolType,
        address: tableData.value[i].protocolAddress,
        num: tableData.value[i].protocolNumber
      });
    }
    console.log("readInfo:", readInfo); // 检查 readInfo 的内容
    let tableData2String = readInfo
      .map(item => `${item.type},${item.address},${item.num}`)
      .join(";");
    console.log("tableData2String:", tableData2String);
    let MQTTObj = {
      slave_address: ruleFormLeft.value.passiveAddress, //从站地址
      groups_num: tableData.value.length, //几行数据
      read_info: readInfo //几行数据展示
    };
    let SQLObj = {
      ...selectedKey.value[0],
      ...ruleFormLeft.value,
      updateUser: tableData2String
    };
    let FormObj = {
      MQTTObj: MQTTObj,
      SQLObj: SQLObj
    };
    emit("childFormObj", FormObj); // 触发事件，传递 FormObj 对象作为参数
  } else {
    message("请填写所有的数据", { type: "warning" });
  }
};
// 父组件调用清空函数
const clearVar = () => {
  const storeFormLeft = { ...drawerStore.ruleFormLeft };
  const storeRTUForm = { ...drawerStore.RTUForm };
  ruleFormLeftRef.value.resetFields();
  ruleFormRef.value.resetFields();
  drawerStore.ruleFormLeft = { ...storeFormLeft };
  drawerStore.RTUForm = { ...storeRTUForm };
  tableData.value = [];
};
// 父组件调用保存函数
const saveStore = () => {
  drawerStore.ruleFormLeft = { ...ruleFormLeft.value };
  drawerStore.RTUForm = { ...ruleForm.value };
  drawerStore.tableData = tableData.value;
};
// 父组件调用赋值函数
const copyStore = () => {
  if (devVarTableSelectedItem.value.state === 1) {
    ruleFormLeft.value.passiveAddress =
      devVarTableSelectedItem.value.passiveAddress;
    ruleForm.value = {
      protocolType: devVarTableSelectedItem.value.protocolType,
      protocolAddress: devVarTableSelectedItem.value.protocolAddress,
      protocolNumber: devVarTableSelectedItem.value.protocolNumber
    };
    const connectorData = devVarTableSelectedItem.value.updateUser;

    if (connectorData) {
      const rows = connectorData.split(";").map(row => {
        const [protocolType, protocolAddress, protocolNumber] = row.split(",");
        return {
          protocolType,
          protocolAddress,
          protocolNumber
        };
      });

      tableData.value = rows; // 更新 tableData
    } else {
      tableData.value = undefined; // 如果没有 connector 数据，清空表格
    }
  } else {
    ruleFormLeft.value = drawerStore.ruleFormLeft;
    tableData.value = drawerStore.tableData;
    ruleForm.value = drawerStore.RTUForm;
  }
};
defineExpose({
  clearVar,
  saveStore,
  copyStore
});
</script>

<template>
  <div class="form-main">
    <el-form ref="ruleFormLeftRef" :model="ruleFormLeft" :inline="false">
      <el-form-item label="从站地址" prop="passiveAddress">
        <el-input
          v-model="ruleFormLeft.passiveAddress"
          clearable
          placeholder="请输入从站地址"
        />
      </el-form-item>
    </el-form>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :inline="true"
      label-position="top"
    >
      <el-form-item
        label="类型"
        prop="protocolType"
        style="width: 110px; margin-right: 20px"
      >
        <el-select v-model="ruleForm.protocolType" placeholder="请选择类型">
          <el-option label="coil" value="coil" />
          <el-option label="reg" value="register" />
        </el-select>
      </el-form-item>
      <el-form-item
        label="地址"
        prop="protocolAddress"
        style="width: 110px; margin-right: 20px"
      >
        <el-input v-model="ruleForm.protocolAddress" placeholder="请输入地址" />
      </el-form-item>
      <el-form-item
        label="数量"
        prop="protocolNumber"
        style="width: 110px; margin-right: 20px"
      >
        <el-input v-model="ruleForm.protocolNumber" placeholder="请输入数量" />
      </el-form-item>
      <el-form-item style="width: 50px">
        <el-button type="primary" class="form-btn" @click="confirmClick"
          >确定</el-button
        >
      </el-form-item>
      <el-form-item style="width: 50px; margin-right: 0px">
        <el-button type="primary" class="form-btn" @click="deleteClick"
          >删除</el-button
        >
      </el-form-item>
    </el-form>
    <div class="form-table">
      <el-table
        ref="multipleTableRef"
        class="custom-table"
        :data="tableData"
        border
        stripe
        max-height="200"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column prop="protocolType" label="类型" align="center" />
        <el-table-column prop="protocolAddress" label="地址" align="center" />
        <el-table-column prop="protocolNumber" label="数量" align="center" />
      </el-table>
    </div>
    <div class="config-btn">
      <el-button type="primary" @click="configClick">配置</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.form-btn {
  margin-top: 30px;
}

.form-table {
  padding-bottom: 20px;
}

.config-btn {
  text-align: right;
}
</style>
